package sk.fritz.megafonsms.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Image;

import sk.fritz.megafonsms.formmodel.AbstractFormControl;
import sk.fritz.megafonsms.formmodel.FormModel;


public class Util {
	
	public static Hashtable readProperties(InputStream input) {
		Reader r = new InputStreamReader(input);
		Hashtable res = new Hashtable();
		int i;
		try {
			StringBuffer buff = new StringBuffer();
			while ((i = r.read()) != -1) {
				char ch = (char) i;
				if (ch == '\n'){
					String s = buff.toString();
					buff.delete(0, buff.length());
					int indx = s.indexOf('=');
					String value = s.substring(indx+1);
					String key = s.substring(0, indx);
					res.put(key, value);
				} else {
					buff.append(ch);
				}
			}
		} catch (IOException e) {
		}
		return res;
	}
	
	public static Image downloadImage(String url) {
		HttpConnection connection = null;
		InputStream inputStream = null;
		try {
			connection = (HttpConnection) Connector.open(url);
			connection.setRequestProperty("Connection", "close");
			inputStream = connection.openInputStream();		
			byte[] data = readFromInputStream(inputStream);
			return Image.createImage(data, 0, data.length);

		} catch (IOException ex) {
			System.out.println("Exception while downloading image :"
					+ ex.getMessage());
			return null;
		} finally {
				if (inputStream != null)
					try {
						inputStream.close();
					} catch (IOException e) {}
				if (connection != null)
					try {
						connection.close();
					} catch (IOException e) {}
		}
	}
	
	public static String sendForm(FormModel model, String url)
			throws IOException {
		HttpPostRequest req = new HttpPostRequest(url);
		Enumeration en = model.getSuccessfulControls();
		while (en.hasMoreElements()) {
			AbstractFormControl ctrl = (AbstractFormControl) en.nextElement();
			// assume values are correct at this point
			System.out.println(ctrl.getName() + ":" + ctrl.getValue());
			req.setParameter(ctrl.getName(), ctrl.getValue());
		}
		return req.post();
	}
	
	public static byte[] readFromInputStream(InputStream is) throws IOException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		byte[] data = new byte[512];
		int total = 0x00;
		int read  = -1;
		do {
			read = is.read(data);
			if (read > 0x00) {
				total += read;
				buffer.write(data, 0x00, read);
			}
		} while (read != -1);
		buffer.close();
		return buffer.toByteArray();
	}
	
	public static void runAsync(final Runnable operation, final String title,
			final String detail,  final Display disp) {
		Runnable r = new Runnable() {
			
			public void run() {
				// prepare something-is-going-on dialog
				Alert busy = new Alert(title, detail, null, AlertType.INFO);
				Gauge indicator = new Gauge(null, false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING);
				busy.setTimeout(Alert.FOREVER);
				busy.setIndicator(indicator);
				
				disp.setCurrent(busy);
				operation.run();
			}
		};
		
		new Thread(r).start();
	}

}
